﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using CarolLib.Control;
using System.Xml;
using StockMonitor.Helper;
using CarolLib;
using System.Threading;
using StockMonitor.Business;
using StockMonitor.Configuration;

namespace StockMonitor.UserControls
{
    [ModuleContract("2C89BC3D-E108-4f5d-81F9-9832CFF08FE7", "交易(&R)", "自动交易")]
    public partial class UCAutoTrade : MdiUserControl
    {
        HsGateway hs = new HsGateway();

        #region Ctor.

        public UCAutoTrade()
            : base()
        {
            InitializeComponent();

            Log.OnLogged += new EventHandler<LogEventArgs>(Log_OnLogged);
        }

        public UCAutoTrade(XmlNode node)
            : this()
        {
            InitializeComponent();
        }

        #endregion

        #region Members

        /// <summary>
        /// 自动交易是否启动（与GlobalStatusContext.AutoTradeStarted同步）
        /// </summary>
        /// <remarks>
        /// 代码编写：<author>LANCEZHANG-PC\zhangxl</author><br/>
        /// 编写时间：<datetime>2012-10-16 5:33 PM</datetime>
        /// </remarks>
        bool tradeStarted = false;
        bool TradeStarted
        {
            get { return tradeStarted; }
            set
            {
                tradeStarted = value;
                GlobalStatusContext.AutoTradeStarted = tradeStarted;
            }
        }

        /// <summary>
        /// 自动交易线程
        /// </summary>
        /// <remarks>
        /// 代码编写：<author>LANCEZHANG-PC\zhangxl</author><br/>
        /// 编写时间：<datetime>2012-10-16 5:33 PM</datetime>
        /// </remarks>
        Thread threadAutoTrade;

        #endregion

        #region EventHandler

        private void btnAddStockInPool_Click(object sender, EventArgs e)
        {
            bool isBuy = (sender as Button).Tag.ToString() == "1";

            Forms.frmEditStockInPool dlg = new Forms.frmEditStockInPool(isBuy, ReLoadPoolItemUI);
            dlg.ShowDialog();
        }

        private void btnEditStockInPool_Click(object sender, EventArgs e)
        {
            bool isBuy = (sender as Button).Tag.ToString() == "1";
            DataGridView dv = isBuy ? this.dgvBuy : this.dgvSell;
            if (dv.SelectedRows.Count == 0)
                return;
            string stockCode = dv.SelectedRows[0].Cells[0].Value.ToString();

            Forms.frmEditStockInPool dlg = new Forms.frmEditStockInPool(isBuy, stockCode, ReLoadPoolItemUI);
            dlg.ShowDialog();
        }

        private void btnDelStockInPool_Click(object sender, EventArgs e)
        {
            bool isBuy = (sender as Button).Tag.ToString() == "1";
            DataGridView dv = isBuy ? this.dgvBuy : this.dgvSell;
            if (dv.SelectedRows.Count == 0)
                return;

            string stockCode = dv.SelectedRows[0].Cells[0].Value.ToString();

            if (MessageBox.Show("您确定要删除这条配置吗？", "删除确认", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) != DialogResult.OK)
                return;

            StockPoolItem item = StockPool.Instance.Pool.Find(s => s.StockCode == stockCode && s.IsBuy == isBuy);
            StockPool.Instance.Pool.Remove(item);
            StockPool.Instance.Save();
            ReLoadPoolItemUI(item);
        }

        /// <summary>
        /// Handles the Tick event of the timerUpdateUI control.
        /// 1. 刷新余额
        /// 2. 刷新累计成交
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        /// <remarks>
        /// 代码编写：<author>LANCEZHANG-PC\zhangxl</author><br/>
        /// 编写时间：<datetime>2012-10-16 5:38 PM</datetime>
        /// </remarks>
        private void timerUpdateUI_Tick(object sender, EventArgs e)
        {
            ThreadPool.QueueUserWorkItem(o =>
            {
                while (!this.IsHandleCreated)
                    Thread.Sleep(100);

                this.Invoke(new Action(() =>
                {
                    this.dgvAccountInfo["CurrentBalance", 0].Value = AuthUserContext.Instance.CurrentBalance;
                    this.dgvAccountInfo["EnableBalance", 0].Value = AuthUserContext.Instance.EnableBalance;
                    this.dgvAccountInfo["FetchCash", 0].Value = AuthUserContext.Instance.FetchCash;
                    this.dgvAccountInfo["AssetBalance", 0].Value = AuthUserContext.Instance.AssetBalance;

                    this.dgvAccountInfo.Update();
                    this.dgvAccountInfo.Refresh();

                    for (int i = 0; i < this.dgvSell.RowCount; i++)
                        this.dgvSell["col1TodayExchangeSummary", i].Value = StockPool.Instance.SellPool[i].TodayExchangeSummary;

                    for (int i = 0; i < this.dgvBuy.RowCount; i++)
                        this.dgvBuy["col2TodayExchangeSummary", i].Value = StockPool.Instance.BuyPool[i].TodayExchangeSummary;

                    this.dgvBuy.Update();
                    this.dgvSell.Refresh();
                    this.dgvSell.Update();
                    this.dgvSell.Refresh();
                }));

            });

            this.chk3521.Enabled = !this.TradeStarted;
            this.btnStartAutoTrade.Enabled = !this.TradeStarted;
            this.btnEditSell.Enabled = !this.TradeStarted;
            this.btnAddBuy.Enabled = !this.TradeStarted;
            this.btnEditBuy.Enabled = !this.TradeStarted;
            this.btnDelBuy.Enabled = !this.TradeStarted;
            this.btnStopAutoTrade.Enabled = this.TradeStarted;

            //LoadModelsInfo();
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("您确定要退出程序吗？", "退出确认", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation) == DialogResult.OK)
            {
                Log.Info("退出系统");
                Application.Exit();
            }
        }

        private void btnStartAutoTrade_Click(object sender, EventArgs e)
        {
            StringBuilder sb = new StringBuilder("请确认以下配置信息\n\n进行检测的指标：\n");
            bool check = false;
            foreach (var item in this.groupBox2.Controls)
            {
                if ((item is CheckBox) && (item as CheckBox).Checked)
                {
                    if ((item as CheckBox).Text == "MA均线组合")
                    {
                        sb.AppendLine(" " + AppSettings.GetValue<string>("MAParams", "3|5|21", true) + "均线组合");
                    }
                    else
                    {
                        sb.AppendLine(" " + (item as CheckBox).Text);
                    }
                    check = true;
                }
            }

            if (!check)
            {
                MessageBox.Show("请至少选中一个指标进行检测", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            sb.AppendLine("\n自动买入股票配置：");
            StockPool.Instance.BuyPool.ForEach(s => sb.AppendLine(string.Format(" {0}({1} 买入价格:{2} 买入数量:{3} 加仓数量:{4})", s.StockCode, s.StockName, s.ExchangePriceType, s.ExchangeAmount, s.AppendAmount)));

            sb.AppendLine("\n自动卖出股票配置：");
            StockPool.Instance.SellPool.ForEach(s => sb.AppendLine(string.Format(" {0}({1} 卖出价格:{2} 卖出数量:{3} 减仓数量:{4}) 当前数量:{5} 可卖数量:{6} ", s.StockCode, s.StockName, s.ExchangePriceType, s.ExchangeAmount, s.AppendAmount, s.CurrentAmount, s.EnableAmount)));

            if (MessageBox.Show(sb.ToString(), "自动交易配置确认", MessageBoxButtons.OKCancel) == DialogResult.Cancel)
                return;

            if (GlobalStatusContext.LimitedTradeStarted)
            {
                if (MessageBox.Show("限价交易正在进行中，您确定要开启自动交易吗？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation) == DialogResult.Cancel)
                    return;
            }

            Log.Info("自动交易已开始");
            this.TradeStarted = true;

            threadAutoTrade = new Thread(new ThreadStart(AutoTrade));
            threadAutoTrade.IsBackground = true;
            threadAutoTrade.Priority = ThreadPriority.Highest;
            threadAutoTrade.Start();
        }

        private void btnStopAutoTrade_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("确定要停止自动交易吗？", "确认", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation) == DialogResult.OK)
            {
                this.TradeStarted = false;
                Log.Info("自动交易已停止");
            }
        }

        /// <summary>
        /// Handles the Click event of the btnRefresh control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        /// <remarks>
        /// 代码编写：<author>LANCEZHANG-PC\zhangxl</author><br/>
        /// 编写时间：<datetime>2012-10-16 5:37 PM</datetime>
        /// </remarks>
        private void btnRefresh_Click(object sender, EventArgs e)
        {
            Onload();
        }

        #endregion

        #region MdiUserControl Members

        /// <summary>
        /// 窗体加载.
        /// 刷新今日成交记录。
        /// </summary>
        /// <remarks>
        /// 代码编写：<author>LANCEZHANG-PC\zhangxl</author><br/>
        /// 编写时间：<datetime>2012-10-16 5:40 PM</datetime>
        /// </remarks>
        public override void Onload()
        {
            this.lbUserAccount.Text = AuthUserContext.Instance.FundAccount;
            this.lbUserName.Text = AuthUserContext.Instance.ClientName;

            AuthUserContext[] info = { AuthUserContext.Instance };
            this.dgvAccountInfo.AutoGenerateColumns = false;
            this.dgvAccountInfo.DataSource = info;

            this.dgvBuy.AutoGenerateColumns = false;
            this.dgvSell.AutoGenerateColumns = false;
            LoadStockPool();

            //Load Model's Init infor.
            //LoadModelsInfo();

            //create connection.
            hs.Connect();

            try
            {
                TradeContext.Instance.UpdateTodayBusiness();
                RefreshStockPositionUI();
            }
            catch (HsGateway.HsCommException hsex)
            {
                Log.Exception("交易接口返回错误", hsex);
            }
            catch (Exception ex)
            {
                Log.Exception("系统错误", ex);
            }
        }

        /// <summary>
        /// 窗体卸载.
        /// </summary>
        /// <remarks>
        /// 代码编写：<author>LANCEZHANG-PC\zhangxl</author><br/>
        /// 编写时间：<datetime>2012-10-16 5:40 PM</datetime>
        /// </remarks>
        public override void Unload()
        {
            base.Unload();
            hs.Dispose();
        }

        #endregion

        #region Methods.

        /// <summary>
        /// 根据股票池更新股票池显示的UI，用于弹出窗回调
        /// </summary>
        /// <param name="item">股票池元素.</param>
        /// <remarks>
        /// 代码编写：<author>LANCEZHANG-PC\zhangxl</author><br/>
        /// 编写时间：<datetime>2012-10-16 5:51 PM</datetime>
        /// </remarks>
        public void ReLoadPoolItemUI(StockPoolItem item)
        {
            if (item.IsBuy)
            {
                this.dgvBuy.DataSource = StockPool.Instance.BuyPool;
            }
            else
            {
                this.dgvSell.DataSource = StockPool.Instance.SellPool;
            }
        }

        /// <summary>
        /// 根据股票池更新股票池显示的UI.
        /// </summary>
        /// <remarks>
        /// 代码编写：<author>LANCEZHANG-PC\zhangxl</author><br/>
        /// 编写时间：<datetime>2012-10-16 5:53 PM</datetime>
        /// </remarks>
        public void LoadStockPool()
        {
            this.dgvBuy.DataSource = StockPool.Instance.BuyPool;
            this.dgvSell.DataSource = StockPool.Instance.SellPool;
        }

        /// <summary>
        /// 根据系统配置显示MA的参数到UI.
        /// </summary>
        /// <remarks>
        /// 代码编写：<author>LANCEZHANG-PC\zhangxl</author><br/>
        /// 编写时间：<datetime>2012-10-16 5:54 PM</datetime>
        /// </remarks>
        public void LoadModelsInfo()
        {            
            var maparam = AppSettings.GetValue<string>("MAParams", "3|5|21", true).Split('|').ToList();
            StringBuilder sb = new StringBuilder();
            maparam.ForEach(m => { sb.Append(m); });

            this.chk3521.Text = sb.Append("均线组合").ToString();
        }

        /// <summary>
        /// 刷新股票持仓情况UI，重新绑定GridView.
        /// </summary>
        /// <remarks>
        /// 代码编写：<author>LANCEZHANG-PC\zhangxl</author><br/>
        /// 编写时间：<datetime>2012-10-16 5:26 PM</datetime>
        /// </remarks>
        public void RefreshStockPositionUI()
        {
            if (StockPool.Instance.RefreshStockPosition())
            {
                if (this.dgvSell.InvokeRequired)
                {
                    this.Invoke(new Action(() =>
                    {
                        this.dgvSell.DataSource = StockPool.Instance.SellPool;
                        this.dgvSell.Update();
                        this.dgvSell.Refresh();
                    }));
                }
                else
                {

                    this.dgvSell.DataSource = StockPool.Instance.SellPool;
                    this.dgvSell.Update();
                    this.dgvSell.Refresh();
                }
            }
        }

        /// <summary>
        /// 执行交易操作.
        /// 若交易成功，3秒钟后刷新并显示结果
        /// </summary>
        /// <param name="stock">股票.</param>
        /// <param name="action">交易信号.</param>
        /// <returns></returns>
        /// <remarks>
        /// 代码编写：<author>LANCEZHANG-PC\zhangxl</author><br/>
        /// 编写时间：<datetime>2012-10-16 5:27 PM</datetime>
        /// </remarks>
        private int ExecuteTrade(StockPoolItem stock, Enums.Signal action)
        {
            try
            {
                int result = 0;

                if (stock.IsBuy)
                {
                    result = TradeContext.Instance.BuyOrder(stock.StockCode, action == Enums.Signal.Buy ? stock.ExchangeAmount : stock.AppendAmount, stock.ExchangePriceType);
                }
                else
                {
                    int amount = (action == Enums.Signal.Sell ? stock.ExchangeAmount : stock.AppendAmount);
                    if (amount > stock.EnableAmount)
                    {
                        Log.Info(stock.StockCode + "可卖数量不足，不能进行自动卖出");
                        return -2;
                    }
                    result = TradeContext.Instance.SellOrder(stock.StockCode, amount, stock.ExchangePriceType);
                }

                if (result > 0)
                {
                    ThreadPool.QueueUserWorkItem(o =>
                    {
                        Thread.Sleep(3000);
                        RefreshStockPositionUI();
                        AuthUserContext.Instance.RefreshBalance();
                        TradeContext.Instance.UpdateTodayEntrusts();

                        Log.Info(TradeContext.Instance.TodayEntrusts.Find(t => t.EntrustNo == result).ShowResult());
                    });
                    return result;
                }
                else
                {
                    Log.Info("委托失败，错误代码：" + result.ToString() + result.ToString() == "-2" ? " 可卖数量不足，不能进行自动卖出" : " ");
                    return result;
                }
            }
            catch (HsGateway.HsCommException hsex)
            {
                Log.Exception("交易接口返回错误", hsex);
                return Convert.ToInt32(hsex.ErrorInfo);
            }
            catch (Exception ex)
            {
                Log.Exception("系统错误", ex);
                return -1;
            }
        }

        /// <summary>
        /// 【线程】自动交易.
        /// 1.初始化，为股票池中的每只股票创建MA计算器
        /// 2.批量获取行情，并提供给每个计算器进行计算（信号检测）
        /// 3.将本次得到的信号逐个进行处理（交易）
        /// 4.如果股票池发生变动，保存股票池
        /// 5.休息，等待下次轮循
        /// </summary>
        /// <remarks>
        /// 代码编写：<author>LANCEZHANG-PC\zhangxl</author><br/>
        /// 编写时间：<datetime>2012-10-16 5:33 PM</datetime>
        /// </remarks>
        private void AutoTrade()
        {
            List<string> codes = StockPool.Instance.Pool.Select(s => s.StockCode).Distinct().ToList();

            List<ICaptialCalculator> cals = new List<ICaptialCalculator>();

            if (chk3521.Checked)
            {
                Log.Info("初始化MA均线指标监测程序，参数为：" + AppSettings.GetValue<string>("MAParams", "3|5|21", true) + "...");

                codes.ForEach(c =>
                {
                    var cal = BusinessFactory.GetMACalculator();
                    cal.Init(c);
                    cals.Add(cal);
                });
            }

            while (this.TradeStarted)
            {
                bool needSavePool = false;
                Dictionary<string, Enums.Signal> sigDic = new Dictionary<string, Enums.Signal>();

                Dictionary<string, StockPrice> currentPrices;
                try
                {
                    currentPrices = BusinessFactory.GetCurrentPriceProvider().BatchGetCurrentPrice(codes).ToDictionary(c => c.StockCode);
                }
                catch (Exception e)
                {
                    Log.Exception("行情价格获取失败，请检查系统配置", e);
                    Thread.Sleep(AppSettings.GetValue<int>("SignalDetectInterval", 1000, true));
                    continue;
                }

                cals.ForEach(cal =>
                {
                    try
                    {
                        if (currentPrices.ContainsKey(cal.StockCode))
                        {
                            var signal = cal.DetectSignal(currentPrices[cal.StockCode].Price);

                            if (signal != Enums.Signal.None)
                                sigDic.Add(cal.StockCode, signal);
                        }
                    }
                    catch (Exception e)
                    {
                        Log.Exception(string.Format("检测{0}({1})指标时发生错误", cal.Key, cal.StockCode), e);
                    }
                });

                foreach (var item in sigDic)
                {
                    var stock = item.Value > Enums.Signal.None ? StockPool.Instance.BuyPool.Find(s => s.StockCode == item.Key) : StockPool.Instance.SellPool.Find(s => s.StockCode == item.Key);
                    var stock2 = item.Value < Enums.Signal.None ? StockPool.Instance.BuyPool.Find(s => s.StockCode == item.Key) : StockPool.Instance.SellPool.Find(s => s.StockCode == item.Key);

                    if ((stock != null) && (stock.ExchangePriceType != Enums.PriceType.未设置) && (DateTime.Compare(DateTime.Now, Convert.ToDateTime("9:30:00")) >= 0))
                    {
                        Log.Info(string.Format("{0}({4})检测到{1}指标发出的{2}信号...", stock.StockCode, AppSettings.GetValue<string>("MAParams", "3|5|21", true), item.Value, item.Value, stock.StockName));

                        if ((item.Value == Enums.Signal.Buy || item.Value == Enums.Signal.Sell) && (stock.ExchangeAmount > 0))
                        {
                            //If buy/sell, check last trigger.
                            if (stock.LastTrigger > DateTime.Today || (stock2 != null && stock2.LastTrigger > DateTime.Today)) /////2011年11月2日 买卖互斥:当天买入的股票不能当天卖出，当天卖出的股票不能当天买入
                                continue;

                            //Save last trigger.
                            stock.LastTrigger = DateTime.Now;
                            needSavePool = true;

                            Log.Info(string.Format("{0}({2})进行自动{1}...", stock.StockCode, item.Value, stock.StockName));
                            ExecuteTrade(stock, item.Value);
                        }

                        if ((item.Value == Enums.Signal.BuyAppend || item.Value == Enums.Signal.SellAppend) && stock.AppendAmount > 0)
                        {
                            //If buyAppend/sellAppend, check last trigger.
                            if (stock.LastAppendTrigger > DateTime.Today)
                                continue;

                            //Save last trigger.
                            stock.LastAppendTrigger = DateTime.Now;
                            needSavePool = true;

                            Log.Info(string.Format("{0}({2})进行自动{1}...", stock.StockCode, item.Value, stock.StockName));
                            ExecuteTrade(stock, item.Value);
                        }

                        //Enums.Signal.BuyWithAppend Enums.Signal.SellWithAppend 2011-10-13 12:32:23
                        if (item.Value == Enums.Signal.BuyWithAppend || item.Value == Enums.Signal.SellWithAppend)
                        {
                            if (stock.ExchangeAmount > 0)
                            {
                                //If buy/sell, check last trigge.
                                if (stock.LastTrigger < DateTime.Today)
                                {
                                    //Save last trigge.
                                    stock.LastTrigger = DateTime.Now;
                                    needSavePool = true;

                                    Log.Info(string.Format("{0}({2})进行自动{1}...", stock.StockCode, stock.IsBuy ? Enums.Signal.Buy : Enums.Signal.Sell, stock.StockName));
                                    ExecuteTrade(stock, stock.IsBuy ? Enums.Signal.Buy : Enums.Signal.Sell);
                                }
                            }

                            if (stock.AppendAmount > 0)
                            {
                                //add in 2011-10-19 判断是否购卖
                                if (stock.IsBuy || ((!stock.IsBuy) && stock.EnableAmount >= (stock.ExchangeAmount + stock.AppendAmount)))
                                {
                                    //If buyAppend/sellAppend, check last trigger.
                                    if (stock.LastAppendTrigger > DateTime.Today)
                                        continue;

                                    //Save last trigger.
                                    stock.LastAppendTrigger = DateTime.Now;
                                    needSavePool = true;

                                    Log.Info(string.Format("{0}({2})进行自动{1}...", stock.StockCode, stock.IsBuy ? Enums.Signal.BuyAppend : Enums.Signal.SellAppend, stock.StockName));
                                    ExecuteTrade(stock, stock.IsBuy ? Enums.Signal.BuyAppend : Enums.Signal.SellAppend);
                                }
                            }
                        }
                    }
                }

                if (needSavePool)
                    StockPool.Instance.Save();

                Thread.Sleep(AppSettings.GetValue<int>("SignalDetectInterval", 1000, true));
            }
        }

        #endregion

        #region Log

        private Color GetLogColor(LogLevel level)
        {
            switch (level)
            {
                case LogLevel.Debug:
                    return Color.Cyan;
                case LogLevel.Error:
                    return Color.Red;
                case LogLevel.Fatal:
                    return Color.DarkRed;
                case LogLevel.Info:
                    return Color.Green;
                case LogLevel.Warn:
                    return Color.Red;
                default:
                    return Color.Green;
            }
        }

        private void LogText(string text)
        {
            if (rtbOutputInfo.InvokeRequired)
            {
                this.Invoke(new Action<string, Color>(LogText), text, rtbOutputInfo.ForeColor);
            }
            else
                LogText(text, rtbOutputInfo.ForeColor);
        }

        private void LogText(string text, Color color)
        {

            if (rtbOutputInfo.InvokeRequired)
            {
                this.Invoke(new Action<string, Color>((t, c) =>
                {
                    try
                    {
                        rtbOutputInfo.AppendText(text);
                        rtbOutputInfo.Select(rtbOutputInfo.TextLength - text.Length, text.Length);
                        rtbOutputInfo.SelectionColor = color;
                        rtbOutputInfo.AppendText(Environment.NewLine);

                        rtbOutputInfo.Select(rtbOutputInfo.Text.Length, rtbOutputInfo.Text.Length);
                        rtbOutputInfo.ScrollToCaret();
                    }
                    catch
                    {
                    }
                }), text, color);
            }
            else
            {
                try
                {
                    rtbOutputInfo.AppendText(text);
                    rtbOutputInfo.Select(rtbOutputInfo.TextLength - text.Length, text.Length);
                    rtbOutputInfo.SelectionColor = color;
                    rtbOutputInfo.AppendText(Environment.NewLine);

                    rtbOutputInfo.Select(rtbOutputInfo.Text.Length, rtbOutputInfo.Text.Length);
                    rtbOutputInfo.ScrollToCaret();
                }
                catch
                {
                }
            }
        }

        void Log_OnLogged(object sender, LogEventArgs e)
        {
            this.LogText(string.Format("【{0}】{1}", DateTime.Now.ToString("hh:mm:ss"), e.Message), GetLogColor(e.Level));
#if DEBUG
            if (e.Exception != null)
            {
                this.LogText(string.Format("错误信息：{0}", e.Exception.Message), GetLogColor(e.Level));
            }
#endif
        }

        #endregion

        #region Test

        private void TestTrade()
        {
            if (this.dgvBuy.CurrentRow == null)
                return;

            string code = this.dgvBuy.CurrentRow.Cells[0].Value.ToString();

            var stock = StockPool.Instance.BuyPool.Find(s => s.StockCode == code);

            int result = ExecuteTrade(stock, Enums.Signal.Buy);
        }

        #endregion

    }
}
